﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class Build
{

    [MenuItem("Build/Build")]
    private static void BuildAll()
    {
        AssetDatabase.SaveAssets();
        //UpdateVersion();
        ClearAll();
        BuildToLua();
        BuildToConfig();
        BuildToTarget();
        BuildFilesMD5();
        AssetDatabase.Refresh();
    }

    [MenuItem("Build/Clear")]
    private static void ClearAll()
    {
        if (Directory.Exists(Application.streamingAssetsPath))
            Directory.Delete(Application.streamingAssetsPath, true);
        AssetDatabase.Refresh();
    }

    //[MenuItem("Build/BuildFilesMD5")]
    private static void BuildFilesMD5()
    {
        if (!Directory.Exists(Application.streamingAssetsPath))
            Directory.CreateDirectory(Application.streamingAssetsPath);
        string filesPath = Application.streamingAssetsPath + "/files.txt";
        StreamWriter streamWriter = File.CreateText(filesPath);
        string[] buildFilesPath = new string[0];
        GetDirFilesPath(Application.streamingAssetsPath, ref buildFilesPath);
        for (int i = 0; i < buildFilesPath.Length; i++)
        {

            string filePath = buildFilesPath[i].Replace("\\","/");
            string extension = Path.GetExtension(filePath);
            if (extension != ".manifest" && extension != ".meta" && filePath!= filesPath)
            {
                string md5 = Util.MD5(filePath);
                string writeLine = filePath + "|" + md5;
                writeLine = writeLine.Replace(Application.streamingAssetsPath, string.Empty);
                streamWriter.WriteLine(writeLine);
            }

        }
        streamWriter.Close();
        AssetDatabase.Refresh();
        Debug.Log("Build Files MD5 Succeed");
    }

    private static void GetDirFilesPath(string path, ref string[] buildFilesPath)
    {
        string[] files = Directory.GetFiles(path);
        ArrayUtility.AddRange(ref buildFilesPath, files);
        DirectoryInfo dirInfo = new DirectoryInfo(path);
        DirectoryInfo[] dirs = dirInfo.GetDirectories();
        for (int i = 0; i < dirs.Length; i++)
        {
            GetDirFilesPath(dirs[i].FullName, ref buildFilesPath);
        }
    }

    //[MenuItem("Build/UpdateVersion")]
    private static void UpdateVersion()
    {
        if (!Directory.Exists(Application.streamingAssetsPath))
            Directory.CreateDirectory(Application.streamingAssetsPath);
        string bat = Application.dataPath.Replace("Assets", string.Empty) + "svnVersion.bat";
        System.Diagnostics.Process process = System.Diagnostics.Process.Start(bat);
        process.WaitForExit();
        AssetDatabase.Refresh();
        Debug.Log("Build svnUpdate and writeVersion Succeed");
    }

    //[MenuItem("Build/Lua")]
    private static void BuildToLua()
    {
        string from = Application.dataPath + "/ExternalRes/Lua";
        string to = Application.streamingAssetsPath;
        CopyFolder.Copy(from, to);
        AssetDatabase.Refresh();
        Debug.Log("Build Lua Succeed");
    }

    //[MenuItem("Build/Config")]
    private static void BuildToConfig()
    {
        string from = Application.dataPath + "/ExternalRes/Config";
        string to = Application.streamingAssetsPath;
        CopyFolder.Copy(from, to);
        AssetDatabase.Refresh();
        Debug.Log("Build Config Succeed");
    }

    //[MenuItem("Build/BuildToTarget")]
    private static void BuildToTarget()
    {
#if UNITY_STANDALONE_WIN
        BuildToWinAB();
        Debug.Log("Build WinAB Succeed");
#endif

#if UNITY_ANDROID
        BuildToAndroidAB();
        Debug.Log("Build Android AB Succeed");
#endif

#if UNITY_IOS
        BuildToiOSAB();
        Debug.Log("Build IOS AB Succeed");
#endif
    }

    //[MenuItem("Build/BuildToWinAB")]
    private static void BuildToWinAB()
    {
        BuildPlatform(BuildTarget.StandaloneWindows64);
    }

    //[MenuItem("Build/BuildToAndroidAB")]
    private static void BuildToAndroidAB()
    {
        BuildPlatform(BuildTarget.Android);
    }

    //[MenuItem("Build/BuildToiOSAB")]
    private static void BuildToiOSAB()
    {
        BuildPlatform(BuildTarget.iOS);
    }

    private static void BuildPlatform(BuildTarget buildTarget)
    {
        SetBundlesName();
        string buildPath = Application.streamingAssetsPath;
        if (buildTarget == BuildTarget.StandaloneWindows64)
            buildPath = buildPath + "/Windows";
        else if (buildTarget == BuildTarget.Android)
            buildPath = buildPath + "/Android";
        else if (buildTarget == BuildTarget.iOS)
            buildPath = buildPath + "/iOS";
        if (!Directory.Exists(Application.streamingAssetsPath))
            Directory.CreateDirectory(Application.streamingAssetsPath);
        if (Directory.Exists(buildPath))
            Directory.Delete(buildPath, true);
        if (!Directory.Exists(buildPath))
            Directory.CreateDirectory(buildPath);
        //参数一为打包到哪个路径，参数二压缩选项  参数三 平台的目标
        BuildPipeline.BuildAssetBundles(buildPath, BuildAssetBundleOptions.ChunkBasedCompression, buildTarget);
        AssetDatabase.Refresh();
    }

    //[MenuItem("Build/SetBundlesName")]
    private static void SetBundlesName()
    {
        string[] paths = AssetDatabase.GetAllAssetPaths();
        for (int i = 0; i < paths.Length; i++)
        {
            string path = paths[i];
            if (path.Contains("Assets/ExternalRes/Prefab/"))
            {
                if (path.EndsWith(".txt"))
                    continue;
                AssetImporter importer = AssetImporter.GetAtPath(path);
                path = path.Replace("Assets/ExternalRes/Prefab/", string.Empty);
                if (!path.Contains("."))
                    continue;
                string bundleName = "";
                if (!path.Contains("/") || path.Contains("Atlas/") ||
                    path.Contains("Common/") || path.Contains("Effect/") ||
                    path.Contains("Model/") || path.Contains("Sound/") || path.Contains("Texture/"))
                    bundleName = path;
                else
                    bundleName = path.Split('/')[0]+ ".ab";
                importer.assetBundleName = bundleName.Replace("/", "_").Replace(".prefab", ".ab").Replace(".spriteatlas", ".ab").Replace(".mp3", ".ab").Replace(".wav", ".ab").Replace(".ttf", ".ab").Replace(".jpg", ".ab").Replace(".png", ".ab");
            }
        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}
